# -*-coding:utf-8 -*- python3

"""命令行火车票查看器

Usage:
    tickets [-dgktz] <from> <to> <date>

Options:
    -h, --help 查看帮助
    -d         动车
    -g         高铁
    -k         快速
    -t         特快
    -z         直达

Examples:
    tickets 上海 北京 2016-10-10
    tickets -dg 成都 南京 2016-10-10
"""
import time
import requests
from prettytable import PrettyTable
from colorama import init, Fore
from docopt import docopt
from stations import stations

arguments = docopt(__doc__)
from_name = arguments['<from>']
to_name = arguments['<to>']
train_date = arguments['<date>']
stations2 = {v:k for k,v in stations.items()}
start = time.time()
from_station = stations.get(from_name)
to_station = stations.get(to_name)

if from_station == None or to_station == None:
    print(Fore.RED + '请输入正确的车站名' + Fore.RESET)
    exit()

url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date="+train_date+"&leftTicketDTO.from_station="+from_station+"&leftTicketDTO.to_station="+to_station+"&purpose_codes=ADULT"
r = requests.get(url)
text = r.json()
trains = []
for t in text["data"]["result"]:
    list = t.split("|")
    beizhu = list[1]
    train_no = list[2]
    checi = list[3]
    shifazhan = list[4]
    zhongdianzhan = list[5]
    chufazhan = list[6]
    daodazhan = list[7]
    chufashijian = list[8]
    daodashijian = list[9]
    lishi = list[10]
    ruanwo = list[23] if list[23] != '' else '--'
    dongwo = list[33] if list[33] != '' else '--'
    yingwo = list[28] if list[28] != '' else '--'
    yingzuo = list[29] if list[29] != '' else '--'
    wuzuo = list[26] if list[26] != '' else '--'
    erdeng = list[30] if list[30] != '' else '--'
    yideng = list[31] if list[31] != '' else '--'
    shangwu = list[32] if list[32] != '' else '--'
    chezhan = Fore.GREEN + stations2[chufazhan] + Fore.RESET + "\n" + Fore.RED + stations2[daodazhan] + Fore.RESET
    shijian = Fore.GREEN + chufashijian + Fore.RESET + "\n" + Fore.RED + daodashijian + Fore.RESET
    if lishi == '99:59':
        shijian = lishi = '-----'
    trains.append([checi, chezhan, shijian, lishi, shangwu, yideng, erdeng, ruanwo, yingwo, yingzuo, wuzuo])

header = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 硬座 无座'.split()
pt = PrettyTable()
pt._set_field_names(header)
for train in trains:
    pt.add_row(train)
print(pt)
if trains == []:
    print("很抱歉，按您的查询条件，当前未找到从"+from_name+" 到"+to_name+" 的列车。")
print(u"总共耗时：%f 秒" % (time.time() - start))
